<template>
  <div>
    <el-row>
      <el-col :span="24" style="float: left">
        <span>商家入驻总数 :{{ all }} 家</span>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div id="container">
          <!-- 存放图形的div -->
          <div id="storeEcharts"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "StoreEcharts",
  data() {
    return {
      all: 0,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      await this.initChar();
    },
    async initChar() {
      try {
        this.all = 0; // 重置 all
        const response = await this.$http.get("/saleManagement/store/findSettledMerchants");
        console.log("Response data:", response.data);

        if (response.data && response.data.data) {
          const temp = response.data.data;

          // 假设每个商家入驻的时间是当前日期
          const currentDate = new Date().toISOString().split('T')[0];

          // 使用 reduce 累加所有入驻数量
          this.all = temp.length;

          // 统计每个入驻时间点的入驻数量
          const registerCounts = {};
          temp.forEach(item => {
            if (registerCounts[currentDate]) {
              registerCounts[currentDate]++;
            } else {
              registerCounts[currentDate] = 1;
            }
          });

          // 转换为 ECharts 需要的格式
          const registerTimes = Object.keys(registerCounts).sort();
          const counts = registerTimes.map(time => registerCounts[time]);

          const myChart = this.$echarts.init(document.getElementById('storeEcharts'));
          myChart.setOption({
            title: {
              text: "商家入驻数统计图",
            },
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: ['入驻数']
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: registerTimes
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: "入驻数",
                type: 'line',
                data: counts,
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    fontSize: 15
                  }
                },
                areaStyle: {
                  color: '#8195d3',
                  opacity: 0.5
                }
              }
            ]
          });
        } else {
          console.error("Invalid response data structure");
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    }
  }
};
</script>

<style scoped>
#storeEcharts {
  height: 500px;
  width: 900px;
}

#container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}
</style>